package manage.commons.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import manage.commons.Constants;
import manage.commons.cookie.UserStateSessionManager;
import manage.commons.utils.CookieUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 对未登录直接访问jsp做拦截
 * 
 * @author dongji
 * @since 2012-9-6 下午03:44:28
 */
public class JspAuthorFilter extends OncePerRequestFilter {

	protected static final Log log = LogFactory.getLog(JspAuthorFilter.class);
	private static List<String> staticPage = new ArrayList<String>();
	static {
		staticPage.add(Constants.INDEX_PAGE);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		String curRequestUri = request.getRequestURI();
		String cookieUser = CookieUtils.getCookie(request, Constants.COOKIE_U);
		final UserStateSessionManager sessionManager = new UserStateSessionManager(
				cookieUser);
		if (null == sessionManager.getUserState()) {
			if (staticPage.contains(curRequestUri)
					|| StringUtils.isNotBlank(curRequestUri)
					&& !StringUtils.equals(Constants.LOGIN_PAGE, curRequestUri)
					&& curRequestUri.indexOf(".jsp") > -1) {
				request.getRequestDispatcher(Constants.LOGIN_PAGE).forward(
						request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}
}
